package com.example.lenovo.weiyi;

import android.content.Context;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.com.ruanmeng.demon.ServiceM;
import com.com.ruanmeng.utils.CommonUtil;
import com.com.ruanmeng.utils.PreferencesUtils;
import com.wxpay.WXPayHttp;
import com.yolanda.nohttp.NoHttp;
import com.yolanda.nohttp.rest.Request;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import alipay.PayTool;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import loopview.LoopView;
import loopview.OnItemSelectedListener;
import nohttp.CallServer;
import nohttp.CustomHttpListener;
import share.Const;
import share.HttpIP;

/**
 * Created by Administrator on 2017/5/5.
 */

public class PayServiceActivity extends BaseActivity {
    @BindView(R.id.tv_service)
    TextView tvService;
    @BindView(R.id.ll_service)
    LinearLayout llService;
    @BindView(R.id.tv_money)
    TextView tvMoney;
    @BindView(R.id.ll_money)
    LinearLayout llMoney;
    @BindView(R.id.iv_self_jian)
    ImageView ivSelfJian;
    @BindView(R.id.tv_num)
    TextView tvNum;
    @BindView(R.id.iv_self_jia)
    ImageView ivSelfJia;
    @BindView(R.id.ll_num)
    LinearLayout llNum;
    @BindView(R.id.et_tuijian_person)
    EditText etTuijianPerson;
    @BindView(R.id.ll_tuijian_person)
    LinearLayout llTuijianPerson;
    @BindView(R.id.cb_check_zhifubao)
    CheckBox cbCheckZhifubao;
    @BindView(R.id.ll_zhifubao)
    LinearLayout llZhifubao;
    @BindView(R.id.cb_check_weixin)
    CheckBox cbCheckWeixin;
    @BindView(R.id.ll_weixin)
    LinearLayout llWeixin;
    @BindView(R.id.tv_total_money)
    TextView tvTotalMoney;
    @BindView(R.id.tv_pay_now)
    TextView tvPayNow;
    private PayServiceAdapter payServiceAdapter;
    private List<ServiceM.RowsBean> listService = new ArrayList<>();
    private List<String> listService_name = new ArrayList<>();
    private String price;
    int payType = 0;//0  支付宝    1微信


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_pay_service);
        ButterKnife.bind(this);
        ChangLayTitle("购买服务");
        cbCheckZhifubao.setChecked(true);
    }

    /**
     * 获取数据
     */
    public void getData() {
        Request<String> mRequest = NoHttp.createStringRequest(HttpIP.BuyService, Const.POST);
        mRequest.addHeader("token", PreferencesUtils.getString(PayServiceActivity.this, "uid"));
        // 添加到请求队列
        CallServer.getRequestInstance().add(PayServiceActivity.this, 0, mRequest,
                new CustomHttpListener(PayServiceActivity.this, true, ServiceM.class) {
                    @Override
                    public void doWork(Object data, boolean isOne) {
                        ServiceM model = ((ServiceM) data);
                        listService.clear();
                        listService_name.clear();
                        listService.addAll(model.getRows());
                        for (int i = 0; i < listService.size(); i++) {
                            listService_name.add(listService.get(i).getTitle());
                        }
                        ShowSelectService();
                    }

                    @Override
                    public void onFinally(JSONObject obj) throws JSONException {
                        super.onFinally(obj);
                        if (!("100").equals(obj.getString("msgcode"))) {
                            CommonUtil.showToask(PayServiceActivity.this, obj.getString("msg"));
                        }
                    }
                }, true, true);
    }

    @OnClick({R.id.ll_service, R.id.iv_self_jian, R.id.iv_self_jia, R.id.ll_zhifubao, R.id.ll_weixin, R.id.tv_pay_now})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.ll_service:
                getData();
                break;
            case R.id.iv_self_jian:
                if (TextUtils.isEmpty(tvService.getText().toString())) {
                    CommonUtil.showToask(PayServiceActivity.this, "请选择服务！");
                } else {
                    if (Integer.parseInt(CommonUtil.getTextView(tvNum)) > 1) {
                        tvNum.setText("" + (Integer.parseInt(CommonUtil.getTextView(tvNum)) - 1));
                        tvMoney.setText(Integer.parseInt(CommonUtil.getTextView(tvNum)) * Double.parseDouble(price) + "");
                        tvTotalMoney.setText(CommonUtil.getTextView(tvMoney));
                    }
                }
                break;
            case R.id.iv_self_jia:
                if (TextUtils.isEmpty(tvService.getText().toString())) {
                    CommonUtil.showToask(PayServiceActivity.this, "请选择服务！");
                } else {
                    tvNum.setText("" + (Integer.parseInt(CommonUtil.getTextView(tvNum)) + 1));
                    tvMoney.setText(Integer.parseInt(CommonUtil.getTextView(tvNum)) * Double.parseDouble(price) + "");
                    tvTotalMoney.setText(CommonUtil.getTextView(tvMoney));
                }
                break;
            case R.id.ll_zhifubao:
                cbCheckZhifubao.setChecked(true);
                cbCheckWeixin.setChecked(false);
                payType = 0;
                break;
            case R.id.ll_weixin:
                cbCheckZhifubao.setChecked(false);
                cbCheckWeixin.setChecked(true);
                payType = 1;
                break;
            case R.id.tv_pay_now:
                if (TextUtils.isEmpty(CommonUtil.getTextView(tvService))) {
                    CommonUtil.showToask(PayServiceActivity.this, "请选择服务！");
                    return;
                }
                if (TextUtils.isEmpty(CommonUtil.getTextView(etTuijianPerson))) {
                    CommonUtil.showToask(PayServiceActivity.this, "请输入推荐人！");
                    return;
                }
                if (payType == 0) {
                    PayTool.getInstance().startPay(this, new PayTool.PayCallback() {
                        @Override
                        public void doWork(String payResult, boolean isDone) {
                            if (TextUtils.equals("9000", payResult)) {
                                CommonUtil.showToask(PayServiceActivity.this, "支付成功！");
                               /* Intent intent = new Intent(PayServiceActivity.this, PaySuccessActivity.class);
                                intent.putExtra("price", tvMoney.getText().toString());
                                intent.putExtra("pay_name", tvService.getText().toString());
                                startActivity(intent);*/
                                finish();
                            } else {
                                CommonUtil.showToask(PayServiceActivity.this, "支付失败！");
                            }
                        }
                    }, new String[]{PreferencesUtils.getString(PayServiceActivity.this, "uid"), tvNum.getText().toString(), tvMoney.getText().toString(), tvService.getText().toString(), etTuijianPerson.getText().toString()});
                } else {
                    WXPayHttp.getInstance().WeixinPay(this, new String[]{PreferencesUtils.getString(PayServiceActivity.this, "uid"), tvNum.getText().toString(), tvMoney.getText().toString(), tvService.getText().toString(), etTuijianPerson.getText().toString()});
                }
                break;
        }
    }

    private void ShowSelectService() {
        // 加载布局
        LayoutInflater inflater = LayoutInflater
                .from(PayServiceActivity.this);
        View v = inflater.inflate(R.layout.pop_choose, null);
        LoopView loopView = (LoopView) v
                .findViewById(R.id.loopView);
        View view_opo = (View) v
                .findViewById(R.id.view_opo);
        TextView tv_cancel = (TextView) v
                .findViewById(R.id.tv_cancel);
        // 创建popupwindow对话框
        final PopupWindow pop = new PopupWindow(v, LayoutParams.MATCH_PARENT,
                LayoutParams.MATCH_PARENT);
        pop.setFocusable(true);// 必须有，因为要获得焦点进行输入
        // 设置此参数，点击外边可消失
        pop.setBackgroundDrawable(new BitmapDrawable());
        // 点击其他除了popupwindow对话框的地方就可使popupwindow对话框消失
        pop.setOutsideTouchable(true);
        pop.showAtLocation(tvPayNow, Gravity.CENTER, 0, 0);// 显示位置以某控件为中心
        //设置是否循环播放
        loopView.setNotLoop();
        //滚动监听
        loopView.setListener(new OnItemSelectedListener() {
            @Override
            public void onItemSelected(int index) {
                Log.d("debug", "Item " + index);
                tvService.setText(listService.get(index).getTitle());
                tvMoney.setText(listService.get(index).getPrice());
                tvNum.setText("1");
                price = listService.get(index).getPrice();
                tvTotalMoney.setText(price);
            }
        });
        //设置原始数据
        loopView.setItems(listService_name);
        //设置初始位置
        loopView.setInitPosition(2);
//        //设置字体大小
//        loopView.setTextSize(30);

        view_opo.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                pop.dismiss();
            }
        });
        tv_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pop.dismiss();
                tvService.setText("");
                tvMoney.setText("0.00");
                tvNum.setText("1");
                price = "0.00";
                tvTotalMoney.setText(price);
            }
        });
    }

    class PayServiceAdapter extends BaseAdapter {
        // /////////加载图片
        private List<String> listService;
        private Context mcontext;
        private LayoutInflater mlayoutInflate;

        public PayServiceAdapter(List<String> listService, Context mcontext) {
            super();
            this.listService = listService;
            this.mcontext = mcontext;
            mlayoutInflate = LayoutInflater.from(mcontext);

        }

        @Override
        public int getCount() {
            return listService.size();
        }

        @Override
        public Object getItem(int arg0) {
            return listService.get(arg0);
        }

        @Override
        public long getItemId(int arg0) {
            return arg0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            convertView = LayoutInflater.from(PayServiceActivity.this).inflate(R.layout.item_pay_service, null);
            // 初始化控件
            final TextView tv_item = (TextView) convertView
                    .findViewById(R.id.tv_item_pay_service);
            View line_padding = (View) convertView.findViewById(R.id.line_padding);
            View line_match = (View) convertView.findViewById(R.id.line_match);
            if ((position + 1) == listService.size()) {
                line_match.setVisibility(View.VISIBLE);
                line_padding.setVisibility(View.GONE);
            } else {
                line_padding.setVisibility(View.VISIBLE);
                line_match.setVisibility(View.GONE);
            }
            tv_item.setText(listService.get(position));
            return convertView;
        }

    }
}
